/*
 * $Id: UserQuery.java 17 2014-08-28 10:52:50Z ratking $
 *
 * Copyleft (C) 2014 RatKing. All wrongs reserved.
 */
package cn.ratking.demo.jaws7.system.view;

import java.io.Serializable;
import java.util.List;
import java.util.Map;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.enterprise.event.Event;
import javax.inject.Inject;
import javax.inject.Named;

import org.omnifaces.cdi.ViewScoped;
import org.omnifaces.util.Messages;
import org.primefaces.model.LazyDataModel;
import org.primefaces.model.SortOrder;
import org.slf4j.Logger;

import cn.ratking.demo.jaws7.model.LogEvent;
import cn.ratking.demo.jaws7.model.User;
import cn.ratking.demo.jaws7.system.vo.UserSearchCriteria;
import cn.ratking.demo.jaws7.system.service.UserService;

/**
 * 用户查询
 */
@Named
@ViewScoped
public class UserQuery implements Serializable {

    @Inject
    private transient Logger log;
    /** 事件源 */
    @Inject
    private Event<LogEvent> logEventSrc;
    @Inject
    private transient UserService userService;
    @Inject
    private UserSearchCriteria searchCriteria;
    private User selectedUser;
    private LazyDataModel<User> resultModel;

    @PostConstruct
    public void init() {
        log.debug("Debug: UserQuery.init(), this=" + this);
    }

    @PreDestroy
    public void destroy() {
        log.debug("Debug: UserQuery.destroy(), this=" + this);
    }

    public User getSelectedUser() {
        log.debug("Debug: UserQuery.getSelectedUser(), selectedUser=" + selectedUser);
        return selectedUser;
    }

    public void setSelectedUser(User selectedUser) {
        this.selectedUser = selectedUser;
        log.debug("Debug: UserQuery.setSelectedUser(), selectedUser=" + selectedUser);
    }

    /**
     * 懒加载获得结果列表
     *
     * @return 结果列表
     */
    public LazyDataModel<User> getResultModel() {
        if (resultModel == null) {
            log.debug("Debug: UserQuery.getResultModel(), resultModel = new LazyDataModel<User>()");
            resultModel = new LazyDataModel<User>() {
                @Override
                public List<User> load(int first, int pageSize,
                        String sortField, SortOrder sortOrder,
                        Map<String, Object> filters) {
                    log.debug("Debug: UserQuery.getResultModel().load(), first=" + first + ", pageSize=" + pageSize);
//                    int rowCount = this.getRowCount();
//                    if (rowCount == 0) {
//                        return new ArrayList<User>(0);
//                    }
//                    if (first >= rowCount) {
//                        // 当查询使用的首记录超出记录总数时，调整首记录
//                        if (rowCount % pageSize == 0) {
//                            first = ((rowCount / pageSize) - 1) * pageSize;
//                        } else {
//                            first = (rowCount / pageSize) * pageSize;
//                        }
//                    }
                    return userService.getResultList(first, pageSize,
                            sortField, sortOrder, searchCriteria);
                }

                @Override
                public User getRowData(String rowKey) {
                    return (User) userService.findById(Long.valueOf(rowKey));
                }

                @Override
                public Object getRowKey(User object) {
                    return object.getUserId().toString();
                }
            };

            //log.debug("Debug: UserQuery.getResultModel(), resultModel.setRowCount(), rowCount=" + userService.getRowCount(searchCriteria));
            resultModel.setRowCount(userService.getRowCount(searchCriteria));
//            // Arbitrary value only for test purposes.
//            // @see http://forum.primefaces.org/viewtopic.php?f=3&t=4956
            //resultModel.setPageSize(20);
        }
        return resultModel;
    }

    public void search() {
        refresh();
    }

    private void refresh() {
        resultModel = null;
    }

    /**
     * 根据ID删除用户
     *
     * @param userId 用户ID
     */
    public void deleteById(Long userId) {
        userService.deleteById(userId);
        String msg = "删除用户[" + userId + "]成功";
        log.debug(msg);
        logEventSrc.fire(new LogEvent(LogEvent.LOGTYPE_SECURITY, LogEvent.LOGLEVEL_ERROR, msg));
        Messages.addGlobalInfo(msg);
        refresh();
    }
}
